/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.x3.purchasing.login;

import com.x3.purchasing.account.Account;
import com.x3.purchasing.account.AccountDAO;
import com.x3.purchasing.account.AccountDAOImpl;
import com.x3.purchasing.vendor.Vendor;
import com.x3.purchasing.vendor.VendorDAO;
import com.x3.purchasing.vendor.VendorDAOImpl;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

/**
 *
 * @author Hendro Steven
 */
public class LoginWnd extends Window {

    Textbox txtboxUserName;
    Textbox txtboxPassword;
    Session session;
    Account acc;

    public void onCreate() throws Exception {
        session = Sessions.getCurrent();
        txtboxUserName = (Textbox) getFellow("txtboxUserName");
        txtboxPassword = (Textbox) getFellow("txtboxPassword");
        txtboxUserName.setFocus(true);
    }

    public void login() throws Exception {
        try {
            AccountDAO dao = new AccountDAOImpl();
            if (!txtboxUserName.getValue().isEmpty() && !txtboxPassword.getValue().isEmpty()) {
                acc = dao.login(txtboxUserName.getValue(), txtboxPassword.getValue());
                if (acc != null) {
                    if (acc.getRole().getId() == 2) {
                        VendorDAO vDao = new VendorDAOImpl();
                        Vendor vendor = vDao.getByAccount(acc.getId());
                        if (vendor.getStatus() == 0) {
                            Messagebox.show("Account anda blum diaktifkan..");
                            txtboxUserName.setFocus(true);
                        } else {
                            session.setAttribute("ACC_LOGIN", acc);
                            this.detach();
                            Executions.sendRedirect("/index.zul");
                        }
                    } else {
                        session.setAttribute("ACC_LOGIN", acc);
                        this.detach();
                        Executions.sendRedirect("/index.zul");
                    }

                } else {
                    Messagebox.show("Username atau Password anda salah");
                    txtboxUserName.setFocus(true);
                }
            } else {
                Messagebox.show("Silahkan Input Username dan Password");
                txtboxUserName.setFocus(true);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            Messagebox.show("Login Gagal: Username atau password salah");
        }
    }

    public void batal() throws Exception {
        this.detach();
    }
}
